import xml.etree.ElementTree as ET
import re
class OutputGenerator:
    def __init__(self):
        pass

    def generate_nlp_output(self, content):
        # Check if content is XML (starts with < and contains >)
        if isinstance(content, str) and content.strip().startswith('<') and '>' in content.strip():
            try:
                # Attempt to parse as XML to confirm it's valid XML
                ET.fromstring(content.strip())
                return content # Return XML as is, do not format as code
            except ET.ParseError:
                pass # Not valid XML, continue to code detection

        # More robust Python code detection using regex for keywords and indentation
        python_keywords = [r'\bdef\b', r'\bclass\b', r'\bimport\b', r'\bfrom\b', r'\breturn\b', r'\bif\b', r'\belif\b', r'\belse\b', r'\bfor\b', r'\bwhile\b', r'\btry\b', r'\bexcept\b', r'\bfinally\b', r'\bwith\b']
        has_keyword = any(re.search(keyword, content) for keyword in python_keywords)
        has_indentation = re.search(r'^ {4}|\t', content, re.MULTILINE)

        if isinstance(content, str) and (has_keyword or has_indentation):
            return f"```python\n{content}\n```"
        return str(content)

    def generate_structured_xml_output(self, data, root_tag="result"):
        root = ET.Element(root_tag)
        self._build_xml_element(root, data)
        return ET.tostring(root, encoding='unicode')

    def _build_xml_element(self, parent_element, data):
        if isinstance(data, dict):
            for key, value in data.items():
                element = ET.SubElement(parent_element, key)
                self._build_xml_element(element, value)
        elif isinstance(data, list):
            for item in data:
                element = ET.SubElement(parent_element, "item") # Use a generic tag for list items
                self._build_xml_element(element, item)
        else:
            parent_element.text = str(data)

    def generate_markdown_output(self, data):
        if isinstance(data, list) and all(isinstance(i, dict) for i in data):
            # Format as a Markdown table
            if not data:
                return "Empty table."
            headers = data[0].keys()
            table = f"| {' | '.join(headers)} |\n"
            table += f"| {' | '.join(['---'] * len(headers))} |\n"
            for row in data:
                table += f"| {' | '.join(str(row.get(h, '')) for h in headers)} |\n"
            return table
        elif isinstance(data, dict):
            # Format as a Markdown list
            md_list = ""
            for key, value in data.items():
                md_list += f"- **{key}:** {value}\n"
            return md_list
        else:
            return str(data)

    def generate_execution_log(self, log_entry):
        # This could write to a file or a database in a real system
        # For now, we'll just return the log entry as a string
        return str(log_entry)
